import Mocha from '../../modules/mocha.js';
import Config from '../../modules/config.js';
import RTLog from '../../modules/rt_log.js';
import Util from '../../modules/util.js';
import FunctionThrottle from '../../modules/function_throttle';
import ProductResultCache from '../../modules/product_result_cache.js';
import { login } from '../../modules/user_login.js';
let interstitialAd = null;
const App = getApp();

Page({
    mpid: '',
    data: {
        showCustomAd: false,
        productAdvertiseList: [],
        adUnitId: null,
        interstitialAd: null, // 插屏广告
        themeColor: getApp().globalData.themeColor,
        isFromHome: false
    },
    onLoad(options) {
        wx.setNavigationBarTitle({
            title: App.globalData.testTitle
        });
        this.setData({
            isFromHome: Number(options.is_from_home)
        });
        if (options.scene) {
            const data = decodeURIComponent(options.scene).replace(/'/g, '').split('=');
            this.mpid = data[0] === 'mpid' ? data[1] : options.mpid;
        } else {
            this.mpid = options.mpid;
        }
        Mocha.setLatestMp(this.mpid);
        if (options.enable_cache_result === '1') {
            let res = ProductResultCache.getResult(this.mpid);

            if (res && res.url) {
                wx.redirectTo({
                    url: `/pages/result/result?mpid=${this.mpid}&url=${encodeURIComponent(res.url)}`
                });
            }
        } else {
            this.xiguaAdMgrPool = getApp().$modules.advertise.getActivateVideoAdPool();
            wx.showLoading({
                title: '加载中...',
                task: true
            });
            Mocha.getProductConfig(this.mpid)
                .then((data) => {
                    data.h5_config = data.h5_config || {};
                    App.globalData.productInfo = data;
                    wx.setNavigationBarTitle({
                        title: data.h5_config.title
                    });
                    this.setData({
                        title: data.product_name,
                        thumb: data.h5_config.cover || Config.defaultCover,
                        thumb_begin: data.h5_config.begin_test || ''
                    });
                    this.getShareIMageUrl();
                    getApp().mox.stat(`product page get_mocha_product success`);
                })
                .catch((err) => {
                    wx.hideLoading();
                    // getApp().mox.stat(
                    //     `product page get_mocha_product fail:${err.errMsg || err.msg || '未知错误'}`
                    // );
                    getApp().mox.stat(`product page get_mocha_product fail`);
                    RTLog.error(
                        'product page get_mocha_product fail：',
                        err.errMsg || err.msg || '未知错误'
                    );
                    wx.showModal({
                        title: '错误提示',
                        content: `查询失败，错误:\n ${Util.errorMessageReadable(err.msg || err)}`,
                        showCancel: false,
                        success: () => {
                            wx.reLaunch({
                                url: '/pages/index/index',
                                fail: (err) => {
                                    RTLog.error('relaunch fail! err:', err);
                                }
                            });
                        }
                    });
                });

            Mocha.getAdsConfig()
                .then((ads) => {
                    // 在页面onLoad回调事件中创建激励视频广告实例
                    const ad = ads['pages/product/product'];
                    if (ad && Array.isArray(ad)) {
                        this.setData({ adUnitId: ad[0].ad_id });
                        this.createInterstitialAd(ad);
                    } else if (ad && ad.ad_id) {
                        this.setData({ adUnitId: ad.ad_id });
                    }
                    getApp().mox.stat(`product page get_ads_config success`);
                })
                .catch((err) => {
                    // getApp().mox.stat(
                    //     `product page get_ads_config fail：${err.msg || err.errMsg || '未知错误'}`
                    // );
                    getApp().mox.stat(`product page get_ads_config fail`);
                    RTLog.error(
                        'product page get_ads_config fail：',
                        err.errMsg || err.msg || '未知错误'
                    );
                });

            Mocha.getConfig()
                .then((cfg) => {
                    App.globalData.cfgData = cfg;
                    cfg.theme.main_color &&
                        this.setData({
                            themeColor: cfg.theme.main_color
                        });

                    wx.setNavigationBarColor({
                        frontColor: cfg.theme.navibar_text_color || '#000000',
                        backgroundColor: '#F5F5F5'
                    });
                    getApp().mox.stat(`product page get_mocha_h5_config success`);
                })
                .catch((err) => {
                    // getApp().mox.stat(
                    //     `product page get_mocha_h5_config fail：${err.msg || err.errMsg || '未知错误'}`
                    // );
                    getApp().mox.stat(`product page get_mocha_h5_config fail`);
                    RTLog.error(
                        'product page get_mocha_h5_config fail：',
                        err.errMsg || err.msg || '未知错误'
                    );
                });
        }
    },
    getShareIMageUrl() {
        Mocha.getProductList()
            .then((res) => {
                wx.hideLoading();
                res.forEach((item) => {
                    if (item.mpid === this.mpid) {
                        App.globalData.shareImageUrl = item.thumb;
                    }
                });
                getApp().mox.stat(`product page get_mocha_product success`);
            })
            .catch((err) => {
                wx.hideLoading();
                // getApp().mox.stat(`product page get_mocha_product fail:${err.errMsg || err.msg || '未知错误'}`);
                getApp().mox.stat(`product page get_mocha_product fail`);
                RTLog.error(
                    'product page get_mocha_product fail：',
                    err.errMsg || err.msg || '未知错误'
                );
            });
    },
    createInterstitialAd(ad) {
        if (wx.createInterstitialAd) {
            interstitialAd = wx.createInterstitialAd({
                adUnitId: ad[1].ad_id
            });
            interstitialAd.onLoad(() => {
                if (interstitialAd) {
                    interstitialAd.show().catch((err) => {
                        console.error(err);
                    });
                }
            });
            interstitialAd.onError((err) => {
                console.log('ad onError', err);
            });
        }
    },

    whenAdLoadError() {
        // 微信广告加载失败，显示我们自己的广告
        this.setData({
            showCustomAd: true
        });
    },
    clickProductAd(e) {
        let test = e.currentTarget.dataset.test;
        getApp().$modules.advertise.handleAdClick(test, {
            ActivateVideoAd: this.xiguaAdMgrPool.getActivateVideoAd(test.adId)
        });
    },

    onBegin: FunctionThrottle.throttle(function () {
        if (this.data.isFromHome) {
            login(this.mpid);
        } else {
            wx.navigateTo({ url: `/pages/testing/testing?mpid=${this.mpid}&is_from_home=0` });
            getApp().mox.stat('login success');
        }
    }, 2000)
});
